package hluck.me.srorage.sys.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hluck.me.srorage.sys.common.Constast;
import hluck.me.srorage.sys.common.DataGridView;
import hluck.me.srorage.sys.common.PinyinUtils;
import hluck.me.srorage.sys.common.ResultObj;
import hluck.me.srorage.sys.domain.SysDept;
import hluck.me.srorage.sys.domain.SysRole;
import hluck.me.srorage.sys.domain.SysUser;
import hluck.me.srorage.sys.service.SysDeptService;
import hluck.me.srorage.sys.service.SysRoleService;
import hluck.me.srorage.sys.service.SysUserService;
import hluck.me.srorage.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 老雷
 * @since 2021-02-15
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysUserService userService;
    /**
     * 用户全查询
     */
    @RequestMapping("loadAllUser")
    public DataGridView loadAllUser(UserVo userVo){
        Page<SysUser> page = new Page<>(userVo.getPage(), userVo.getLimit());
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(userVo.getLoginname()),"loginname",userVo.getLoginname()).or().eq(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        wrapper.eq("type", Constast.USER_TYPE_NORMAL);
        wrapper.eq(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        wrapper.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        this.userService.page(page,wrapper);

        List<SysUser> users = page.getRecords();
        for (SysUser user : users) {
            Integer deptid = user.getDeptid();
            if (deptid!=null) {
                SysDept dept = deptService.getById(deptid);
                user.setDeptname(dept.getTitle());
            }
            Integer mgr = user.getMgr();
            if (mgr!=null) {
                SysUser sysUser = userService.getById(mgr);
                user.setLeadername(sysUser.getName());
            }
        }
        return new DataGridView(page.getTotal(),users);
    }

    /**
     * 加载最大的排序码
     */
    @RequestMapping("loadMaxUserOrderNum")
    public Map<String,Object> loadMaxOrderNum(){
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<SysUser> list = userService.list(queryWrapper);
        if (list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else {
            map.put("value",1);
        }

        return map;
    }


    /**
     * 根据部门id查询用户
     */
    @RequestMapping("loadUsersByDeptId")
    public DataGridView loadUsersByDeptId(Integer deptid){
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq(deptid!=null,"deptid",deptid);
        wrapper.eq("available",Constast.AVAILABLE_TRUE);
        wrapper.eq("type",Constast.USER_TYPE_NORMAL);
        List<SysUser> userList = userService.list(wrapper);
        return new DataGridView(userList);
    }

    /**
     * 把用户名转成拼音
     */
    @RequestMapping("changeName")
    public Map<String,Object> changeName(String username){
        HashMap<String, Object> map = new HashMap<>();
        if(null!=username){
            map.put("value", PinyinUtils.getPingYin(username));
        }else {
            map.put("value","");
        }
        return map;
    }

    /**
     * 添加用户
     */
    @RequestMapping("addUser")
    public ResultObj addUser(UserVo userVo){
        try{
            userVo.setType(Constast.USER_TYPE_NORMAL);
            userVo.setHiredate(new Date());
            String salt= IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);
            userVo.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD,salt,2).toString());
            userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 根据用户ID查询一个用户
     */
    @RequestMapping("loadUserById")
    public DataGridView loadUserById(Integer id){
        return new DataGridView(this.userService.getById(id));
    }

    /**
     * 修改用户
     */
    @RequestMapping("updateUser")
    public ResultObj updateUser(UserVo userVo){
        try{
            userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("deleteUser")
    public ResultObj deleteUser(Integer id){
        try{
            userService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 重置用户密码
     */
    @RequestMapping("resetPwd")
    public ResultObj resetPwd(Integer id){
        try{
            SysUser user = new SysUser();
            user.setId(id);
            String salt= IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);
            user.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD,salt,2).toString());
            userService.updateById(user);
            return ResultObj.RESET_SUCCESS;
        }catch (Exception e){
            return ResultObj.RESET_ERROR;
        }
    }

    /**
     * 根据用户id查询角色并选中已拥有的角色
     */
    @RequestMapping("initRoleByUserId")
    public DataGridView initRoleByUserId(Integer id){
        //1.查询所有可用的角色
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Map<String, Object>> listMaps = this.roleService.listMaps(wrapper);
        //2.查询当前用户所拥有的角色Id集合
        List<Integer> currentUserRoleIds=this.roleService.queryUserRoleIdsByUid(id);
        for (Map<String, Object> listMap : listMaps) {
            Boolean LAY_CHECKED=false;
            Integer roleId= (Integer) listMap.get("id");
            for (Integer rid : currentUserRoleIds) {
                if (rid==roleId) {
                    LAY_CHECKED=true;
                    break;
                }
            }
            listMap.put("LAY_CHECKED",LAY_CHECKED);
        }
        return new DataGridView(Long.valueOf(listMaps.size()),listMaps);
    }

    /**
     * 保存用户和角色的关系
     */
    @RequestMapping("saveUserRole")
    public ResultObj saveUserRole(Integer uid,Integer[] ids){
        try {

            this.userService.saveUserRole(uid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }
}

